package dbinit;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.address.model.city.City;
import core.address.model.continent.Continent;
import core.address.model.country.Country;
import core.address.model.region.Region;
import core.address.model.state.State;
import core.util.HibernateCoreUtil;

public class InitCity {
	
	public static City getCityByName(String cityName)
	{
		City cio = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Long uuid = 0L;
		try
		{
			transaction = session.beginTransaction();
			List <City> cios = session.createQuery("from City c where c.cityName='"+cityName+"'").list();
			if(cios.size()!= 0)
			{
				 cio = cios.get(0);
			}
			 
			 transaction.commit();
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
		}
		return cio;
	}
	public static City getCityByUuid(Long uuid)
	{
		City c = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				c = (City) session.get(City.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return c ;
	}

	public static Long doinit(State state ,Region region ,Country country , Continent conti , String cityName)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		City city = getCityByName(cityName);
		if(city == null)
		{
			city = new City();
		}
		city.setCityName(cityName);
		city.setContinent(conti);
		city.setCountry(country);
		city.setRegion(region);
		city.setState(state);
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
		    city  = (City)session.merge(city);
		    uuid = city.getUuid();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid ;
	}

}
